import supApi from "@/api/pur/sup";
import supgoodsApi from "@/api/pur/supgoods";
import dictApi from "@/api/system/dict";
import { getToken } from '@/utils/auth'

export default {
  name: "sup",
  data() {
    return {
      listQuery: {
        limitSup: 20,
        pageSup: 1,
        limitGoods: 20,
        pageGoods: 1,
        current: 1,
        size: 20,
        criteria: {
          supName: "",
          contact: "",
          phone: "",
          goodsName: "",
          address: "",
        },
      },
      formSup: {
        name: "",
        id: "",
        address: "",
        phone: "",
        contact: "",
        email: "",
        remark: "",
        num: "",
        status: "",
      },
      formGoods: {
        supId: "",
        name: "",
        id: "",
        price: "",
        priceUnit: "",
        type: "",
        remark: "",
        status: "0",
        pic: "",
      },
      inputVisible: false,
      inputValue: "",
      rulesSup: {
        name: [
          { required: true, message: "请输入供应商名称", trigger: "blur" },
          {
            min: 2,
            max: 25,
            message: "长度在 2 到 25 个字符",
            trigger: "blur",
          },
        ],
        address: [
          { required: true, message: "请输入供应商地址", trigger: "blur" },
          {
            min: 5,
            max: 48,
            message: "长度在 5 到 48 个字符",
            trigger: "blur",
          },
        ],
      },
      rulesGoods: {
        name: [
          { required: true, message: "请输入供应商名称", trigger: "blur" },
          {
            min: 2,
            max: 25,
            message: "长度在 2 到 25 个字符",
            trigger: "blur",
          },
        ],
        price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(); // 如果值不存在，只检查'required'规则
              }
              if (!Number.isInteger(Number(value))) {
                callback(new Error("请输入有效的整数"));
              } else {
                callback();
              }
            },
            message: "请输入有效的整数",
            trigger: "blur",
          },
        ],
        type: [{ required: true, message: "请选择商品类型", trigger: "blur" }],
      },
      formTitle: null,
      formGoodsTitle: null,
      formVisible: false,
      formGoodsVisible: false,
      showSupDetail: false,
      total: 0,
      listSup: null,
      listGoods: null,
      listLoading: true,
      selRowSup: {},
      selRowGoods: {},
      showWay: true,
      file: "",
      imageUrl: "",
      typeDict: null,
      imagList:[],
      baseUrl:process.env.VUE_APP_BASE_API
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.getTypeDict();
      this.fetchData();
    },
    fetchData() {
      if (this.showWay) {
        this.listQuery.current = this.listQuery.pageSup;
        this.listQuery.size = this.listQuery.limitSup;
      } else {
        this.listQuery.current = this.listQuery.pageGoods;
        this.listQuery.size = this.listQuery.limitGoods;
      }
      this.listLoading = true;
      if (this.showWay) {
        supApi.getList(this.listQuery).then((response) => {
          this.listSup = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        });
      } else {
        supgoodsApi.getList(this.listQuery).then((response) => {
          this.listGoods = response.data.records;
          this.listGoods
          this.total = response.data.total;
          this.listLoading = false;
        });
      }
    },
    formatDate(originVal) {
      const dt = new Date(originVal);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      const hh = (dt.getHours() + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");
      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    search() {
      this.listQuery.current = 1;
      this.fetchData();
    },
    reset() {
      this.listQuery.criteria.supName = "";
      this.listQuery.criteria.contact = "";
      this.listQuery.current = 1;
      this.listQuery.criteria.phone = "1";
      this.listQuery.criteria.address = "";
      this.listQuery.criteria.goodsName = "";
      this.fetchData();
    },
    changeShow() {
      this.listQuery.size = 20;
      this.listQuery.current = 1;
      this.showWay = !this.showWay;
      this.fetchData();
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.selRowSup = currentRow;
    },
    handleCurrentChange2(currentRow, oldCurrentRow) {
      this.selRowGoods = currentRow;
    },
    changeSize(limit) {
      if (this.showWay) {
        this.listQuery.limitSup = limit;
      } else {
        this.listQuery.limitGoods = limit;
      }

      this.fetchData();
    },
    fetchPage(page) {
      if (this.showWay) {
        this.listQuery.pageSup = page;
      } else {
        this.listQuery.pagetGoods = page;
      }
      this.fetchData();
    },
    fetchNext() {
      if (this.showWay) {
        this.listQuery.pageSup += 1;
      } else {
        this.listQuery.pagetGoods += 1;
      }
      this.fetchData();
    },
    fetchPrev() {
      if (this.showWay) {
        this.listQuery.pageSup -= 1;
      } else {
        this.listQuery.pagetGoods -= 1;
      }
      this.fetchData();
    },

    editItemSup(record) {
      record.pid > 0;
      this.selRowSup = record;
      this.editSup(this.selRowSup);
    },
    editSup() {
      if (this.checkSel(this.selRowSup)) {
        this.formTitle = "修改供应商";
        this.formSup = this.selRowSup;
        this.formVisible = true;
      }
    },
    saveSup() {
      let self = this;
      this.$refs["formSup"].validate((valid) => {
        if (valid) {
          supApi.save(this.formSup).then((response) => {
            this.$message({
              message: "提交成功",
              type: "success",
            });
            self.fetchData();
            self.formVisible = false;
          });
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.formSup = {
        name: "",
        id: "",
        address: "",
        phone: "",
        contact: "",
        email: "",
        remark: "",
        num: "",
        status: "0",
      };
    },
    addSup() {
      this.resetForm();
      this.formTitle = "添加供应商";
      this.formVisible = true;
    },
    showItemSup(row) {
      this.formSup = row;
      this.showSupDetail = true;
    },
    removeItemSup(record) {
      record.pid > 0;
      this.selRowSup = record;
      this.removeSup(this.selRowSup);
    },
    
    removeSup() {
      if (this.checkSel(this.selRowSup)) {
        let row = this.selRowSup;
        if (row.status == 0) {
          this.$message({
            message: "启用状态下不能删除",
            type: "warning",
          });
          return;
        }
        const id = row.id;
        this.$confirm("确定删除该记录?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          supApi.remove(id).then((response) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.fetchData();
          });
        });
      }
    },
    editItemGoods(record) {
      record.pid > 0;
      this.selRowGoods = record;
      this.editGoods(this.selRowGoods);
    },
    editGoods(row) {
      this.imageUrl = ''
      this.file = null
      if (this.checkSel(this.selRowGoods)) {
        this.formTitle = "修改商品";
        this.formGoods = row;
        this.formGoods.specification;
      if(!this.formGoods.specification){
        this.formGoods.specification=[]
      }
        this.formGoodsVisible = true;
      }
    },
    checkSel(row) {
      if (row && row.id) {
        return true;
      }
      this.$message({
        message: "请选中操作项",
        type: "warning",
      });
      return false;
    },
    removeItemGoods(record) {
      record.pid > 0;
      this.selRowSup = record;
      this.removeGoods(this.selRowSup);
    },

    removeGoods() {
      if (this.checkSel(this.selRowSup)) {
        let row = this.selRowSup;
        if (row.status == 0) {
          this.$message({
            message: "启用状态下不能删除",
            type: "warning",
          });
          return;
        }
        const id = row.id;
        this.$confirm("确定删除该记录?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          supgoodsApi.remove(id).then((response) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.fetchData();
          });
        });
      }
    },
    changeSupStatus(row) {
      supApi.changeStatus(row.id).then((response) => {
        this.$message({
          message: "提交成功",
          type: "success",
        });
        this.fetchData();
      });
    },
    changeGoodsStatus(row) {
      supgoodsApi.changeStatus(row.id).then((response) => {
        this.$message({
          message: "提交成功",
          type: "success",
        });
        this.fetchData();
      });
    },
    addGoods(row) {
      this.resetGoodsForm();
      this.imageUrl = ''
      this.file = null
      this.formGoods.supId = row.id;
      this.formGoodsTitle = "添加商品";
      this.formGoodsVisible = true;
    },
    resetGoodsForm() {
      this.formGoods = {
        supId: "",
        name: "",
        id: "",
        price: "",
        priceUnit: "",
        type: "",
        remark: "",
        status: "0",
        pic: "",
        specification: [],
      };
    },

    // 覆盖默认的上传行为
    httpRequest(option) {
      this.file = option;
    },
    // 上传前处理
    beforeUpload(file) {
      let fileSize = file.size;
      const FIVE_M = 10 * 1024 * 1024;
      //大于5M，不允许上传
      if (fileSize > FIVE_M) {
        this.$message.error("最大上传10M");
        return false;
      }
      //判断文件类型，必须是xlsx格式
      let fileName = file.name;
      let reg = /^.+(\.png)$/;
      let jpg = /^.+(\.jpg)$/;
      if (!reg.test(fileName) && !jpg.test(fileName)) {
        this.$message.error("只能上传png/jpg!");
        return false;
      }
      //预览
      let url = "";
      let reader = new FileReader();
      reader.readAsDataURL(file);
      let that = this;
      reader.onload = function (e) {
        url = this.result.substring(this.result.indexOf(",") + 1);
        that.$set(that, "imageUrl", "data:image/png;base64," + url);
      };

      return true;
    },
    // 文件数量过多时提醒
    handleExceed() {
      this.$message({ type: "error", message: "最多支持1个附件上传" });
    },
    submitImportForm() {
      //表单验证
      this.$refs["formGoods"].validate((valid) => {
        if (valid) {
         

          //这里根据自己封装的axios来进行调用后端接口
          //判断是否携带文件
          if(this.file){
             // 使用form表单的数据格式
          const params = new FormData();
          
          // 将输入表单数据添加到params表单中
          Object.keys(this.formGoods).forEach((key) => {
            if (key != "specification") {
              let value=null
              if(this.formGoods[key]||this.formGoods[key]=='0' || this.formGoods[key]=='false'){
                params.append(key, this.formGoods[key]);
              }
              
            }
          });
          this.formGoods.specification.forEach((number, index) => {
            params.append(`specification[${index}]`, number);
          });
            // 将上传文件数组依次添加到参数paramsData中
          params.append("file", this.file.file);
             supgoodsApi.addGoodsFile(params).then((data) => {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.$refs.formGoods.resetFields(); //清除表单信息
              this.$refs.upload.clearFiles(); //清空上传列表
              this.file = null; //集合清空
              this.formGoodsVisible = false; //关闭对话框
              this.fetchData();
            });

          }else{
            supgoodsApi.addGoods(this.formGoods).then((data) => {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              this.$refs.formGoods.resetFields(); //清除表单信息
              this.$refs.upload.clearFiles(); //清空上传列表
              this.file = null; //集合清空
              this.formGoodsVisible = false; //关闭对话框
              this.fetchData();
            });
          }
          
        } else {
          return false;
        }
      });
    },
    //获取商品类型
    getTypeDict() {
      // 从后台获取字典列表
      let dictName = "商品类型";
      dictApi.getDicts(dictName).then((response) => {
        this.typeDict = response.data[0].children ?? [];
      });
    },
    getTypeValueDict(num) {
      const arr = this.typeDict
      if(arr){
        for(let i=0;i<arr.length;i++){
          if(arr[i].num == num){
            return arr[i].name
          }
        }
      }
      
    },
    handleClose(tag) {
      this.formGoods.specification.splice(this.formGoods.specification.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let from = this.formGoods.specification;
      let inputValue = this.inputValue;
      if (inputValue) {
        from.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    async getPic(url) {
      const imgUrl = await  supgoodsApi.getFileByPathToBase64(encodeURIComponent(url))
      return imgUrl.data;

    },
    generNum(){
      return Math.floor(Math.random() * 20)
    }
  },
};
